﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AvatarHelper;
using Avatar.Model;

namespace Avatar.ADService
{
    public static class OrderManager
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_adID"></param>
        /// <param name="_periodID"></param>
        /// <param name="_priceID"></param>
        public static Guid AddNewOrder(Guid _adID,int _periodID,Guid _priceID)
        {
            #region 入口检测
            #endregion

            try
            {
                Order _order = new Order();

                _order.ID = Guid.NewGuid();
                _order.ADID = _adID;
                _order.PeriodID = _periodID;
                _order.ADPriceID = _priceID;
                _order.OrderStatusID = DBHelper.Get<OrderStatus>(o => o.Name == "未支付", "获取订单状态信息出错:").ID;
                _order.Date = DateTime.Now;
                _order.Code=CreateCode();;

                using (var _adc = DBHelper.GetDataContext())
                {
                    _adc.Order.InsertOnSubmit(_order);
                    _adc.SubmitChanges();
                }
                return _order.ID;
            }
            catch(Exception _e)
            {
                throw new Exception("添加订单出错:"+_e.Message);
            }
        }
        /// <summary>
        /// 生成订单编号
        /// </summary>
        /// <returns></returns>
        private static string CreateCode()
        {
            string _code = DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString();
            try
            {
                Random _r = new Random();
                _code += _r.Next(0001, 9999);
                var _a = DBHelper.Get<Order>(o => o.Code == _code, "获取订单信息出错:");
                if (_a != null)
                {
                    CreateCode();
                }
            }
            catch (Exception _e)
            {
                throw new Exception("生成订单编号出错:"+_e.Message);
            }

            return _code;
        }
    }
}
